package lil.llahn.security.common.asymmetric.signature;

import lil.llahn.security.common.asymmetric.Algo;
import lil.llahn.security.common.asymmetric.Types;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @ClassName: DSASignatureTools
 * @Description: TODO
 * @Date: 2019/11/8 15:26
 * @Auther: lil
 */
public class DSASignatureTools {
    /**
     * todo 执行签名
     * @param data 原数据
     * @param privateKey 私钥
     * @return
     */
    public static byte[] execute(String data, String privateKey) {
        try {
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
            KeyFactory keyFactory = KeyFactory.getInstance(Algo.DSA.name());
            PrivateKey pk = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
            Signature signature = Signature.getInstance(Types.DSA.SHA1withDSA.name());
            signature.initSign(pk);
            signature.update(data.getBytes());
            return signature.sign();
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    /**
     * todo 验证签名
     * @param data 原数据
     * @param bytes 签名数据
     * @param publicKey 公钥
     * @return
     */
    public static boolean verification(String data, byte[] bytes, String publicKey) {
        try {
            X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
            KeyFactory keyFactory = KeyFactory.getInstance(Algo.DSA.name());
            PublicKey pk = keyFactory.generatePublic(x509EncodedKeySpec);
            Signature signature = Signature.getInstance(Types.DSA.SHA1withDSA.name());
            signature.initVerify(pk);
            signature.update(data.getBytes());
            return signature.verify(bytes);
        }catch (Exception e){
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
